<template>
	<div id="meal_fee_record" class="container">
		<div class="content">
			<!-- <div class="title">{{title}}</div> -->
			<div class="panel">
				<div class="condition">
					<div class="row_one">
						<el-date-picker v-model="month" format="yyyy年MM月" @change="monthChange"
							type="month" id="month" style="width: 1.5rem;" :clearable="false">
				    	</el-date-picker>
				    
						&nbsp;
						<el-select v-model="param.classId" 
								filterable  clearable placeholder="选择班级" style="width: 1.8rem;">
						    <el-option v-for="item in classList" :key="item.classId"
						      		   :label="item.className" :value="item.classId">
						    </el-option>
						</el-select>
						&nbsp;
						<el-input v-model="param.keyword" class="input_search" maxlength="100"
			   				 	  style="width: 2.7rem;" placeholder="搜索 学员/班级名称" clearable  >
			  			</el-input>
			  			&nbsp;
			  			<div class="search_btn" v-if="hasApi('mealFeeRecordList')" @click="search()">搜索</div>
						&emsp;
						<div @click="exportExcel()" v-if="hasApi('mealFeeRecordTemplate')"
						  	 class="download_btn" :style="{cursor : exportstate?'not-allowed' : 'pointer'}">
						  	下载记录模板表
						</div>
						
						<div class="mealStatus">
							<div>用餐</div>
							<div>未用餐</div>
							<div>未出勤，有餐</div>
						</div>
					</div>
				</div>
				
				<div class="chart">
					<div class="chart_left">
						<table class="left_table_head" cellspacing="0">
							<tr class="left_tr_head">
								<td style="width: 0.5rem;">序号</td>
								<td style="width: 1.0rem;">姓名</td>
								<td style="width: 0.7rem;">餐费</td>
								<td style="width: 0.1rem;"></td>
							</tr>
						</table>
						<table class="left_table" cellspacing="0">
							<tr v-for="(item,index) in mealFeeList" class="left_tr" :key="index">
								<td style="width: 0.5rem;">{{param.pageSize * (param.currPage-1) + index + 1}}</td>
								<td style="width: 1.0rem;">{{item.name}}</td>
								<td style="width: 0.7rem;">
									<div class="meal" style="margin-bottom: 0.02rem;">中餐</div>
									<div class="meal">晚餐</div>
								</td>
								<td style="width: 0.1rem;"></td>
							</tr>
						</table>
					</div>
					
					<div class="btn_left" @click="scroll(-1)"></div>
					<div class="btn_right" @click="scroll(1)"></div>
					<div class="chart_center">
						<div class="center_scroll" :style="{width: 0.8*dateList.length+'rem'}">
							<table class="center_table_head" cellspacing="0">
								<tr class="center_tr_head">
									<td v-for="(item,index) in dateList" :class="index<=maxEditeIndex?'allow_edit':''" style="width: 0.8rem;" :key="index"
									 @click="selectMealsByDay(index)">
										<span :class="item.date==today?'today':''">{{item.day}}</span>
									</td>
								</tr>
							</table>
							<table class="center_table" cellspacing="0">
								<tr v-for="(item,index0) in mealFeeList" class="center_tr" :key="index0">
									<td v-for="(meal,index1) in item.lunch" style="width: 0.8rem;" :key="index1">
										<div :id="'mealFeeList-lunch'+index0+index1" :class="getMealClass(meal)" style="margin-bottom: 0.02rem;"
										 @click="setMealClass(index0,index1,'lunch')">
											<div v-if="index1==maxEditeIndex&&meal.isEdit==1" class="edit_mark"></div>
										</div>
										<div :id="'mealFeeList-dinner'+index0+index1" :class="getMealClass(item.dinner[index1])"
										 @click="setMealClass(index0,index1,'dinner')">
											<div v-if="index1==maxEditeIndex&&item.dinner[index1].isEdit==1" class="edit_mark"></div>
										</div>
									</td>
								</tr>
							</table>
						</div>
					</div>
					
					<div class="chart_right">
						<table class="right_table_head" cellspacing="0">
							<tr class="right_tr_head">
								<!-- <td style="width: 0.1rem;"></td> -->
								<td style="width: 0.8rem;">用餐总计</td>
							</tr>
						</table>
						<table class="right_table" cellspacing="0">
							<tr v-for="(item,index) in mealFeeList" :key="index" class="right_tr">
								<td style="width: 0.8rem;">
									<div style="margin-bottom: 0.02rem;">{{item.totalLunch}}</div>
									<div >{{item.totalDinner}}</div>
								</td>
							</tr>
						</table>
					</div>
				</div>
				
				<el-pagination class=" " layout="total, sizes, prev, pager, next, jumper"
			      :current-page="param.currPage" @size-change="pageSizeChange"
		      	  @current-change="pageIndexChange" :total="count">
			    </el-pagination>
			    
			    <div class="submit_btn" v-if="hasApi('mealFeeRecordSave')" @click="saveRecord">提交记录</div>
			</div>
		</div>
		
	</div>
</template>

<script>
	
	
var vm,dict;
var $chartCenter;
export default {
	data : function() {
		return {
			title : this.$route.name,
			param : {
				campusId : this.$store.state.campusId,
				classId : "",
				keyword : "",
				startTime : "",
				endTime: "",
				currPage : 1,
				pageSize : 10
			},
			month : new Date(),
			dateList:[],
			today : tool.DateToString(new Date(),"yyyy-MM-dd"),
			classList: [],//班级列表
			maxEditeIndex:-1,//最大可编辑索引
			mealFeeList : [{
					name: "",
					totalLunch:0,
					totalDinner:0,
					lunch: [],
					dinner : []
				}
			],
			count : null,
			/**未用餐0 用餐1 用餐但未出勤2 无记录3 */
			symbleMap:["no_eat","eat","no_attend","none"],
			exportstate: false, //导出excel按钮状态 true为正在下载
			exportNotification: null, //导出excel状态通知
		}
	},
	computed : {
		
	},
	methods : {
		getdateList : function() {
			//获取当前选择时间
			var now = new Date(this.month);
			now.setMonth(now.getMonth()+1);
			now.setDate(0);
			//获取当月最大天数
			var max = now.getDate();
			//循环生成当月日期
			var list = [];
			for(let i=1; i<=max; i++) {
				now.setDate(i);
				list.push({
					date : tool.DateToString(now, "yyyy-MM-dd"),
					day : i
				});
			}
			return list;
		},
		getdateMap : function() {
			//获取当前选择时间
			var now = new Date(this.month);
			now.setMonth(now.getMonth()+1);
			now.setDate(0);
			//获取当月最大天数
			var max = now.getDate();
			//循环生成当月日期
			var list = {};
			for(let i=1; i<=max; i++) {
				now.setDate(i);
				list[tool.DateToString(now, "yyyy-MM-dd")+' 00:00']=i-1;
			}
			// list.count=max;
			let tk=tool.DateToString(new Date(), "yyyy-MM-dd");//tool.DateToString(new Date(), "yyyy-MM-dd")+' 00:00';
			let cur = tool.DateToString(new Date(this.month), "yyyy-MM");
			if(tk.substr(0,7)==cur){//当月
				vm.maxEditeIndex=list[tk+' 00:00'];
			}
			else if(tk>cur){//以前
				vm.maxEditeIndex=max-1;
			}
			else if(tk<cur){//以后
				vm.maxEditeIndex=-1;
			}
			// debugger
			return list;
		},
		search : function(currPage) {
			vm.param.currPage = currPage || 1;
			
			api.mealFeeRecordList(vm.param).then(function(data) {
				if(data.resultCode==2000){
					let list=data.list;
					let result=[];
					vm.count=data.totalCount;
					let dateMap=vm.getdateMap();
					//格式化数据
					//mealsId mealsTime recordMode studentId studentMealsRecordId
					for(let i=0;i<list.length;i++){
						let rowi=list[i];
						let studentId=rowi.studentId;
						let studentName=rowi.realName;
						let totalLunch=0,totalDinner=0;
						let lunchlist=[],dinnerlist=[];
						let lunchMealsId,dinnerMealsId,lunchEdit=0,dinnerEdit=0;
						rowi.mealsEntityList.forEach(mealsEntity=>{
							//中餐
							if(mealsEntity.type==1){
								lunchMealsId=mealsEntity.mealsId;
								lunchEdit=mealsEntity.isEdit;
							}
							//晚餐
							else{
								dinnerMealsId=mealsEntity.mealsId;
								dinnerEdit=mealsEntity.isEdit;
							}
						});
						for(let kk in dateMap){
							lunchlist.push(new Object({
								mealsId:lunchMealsId,
								mealsTime:kk,
								recordMode:3,
								studentId:studentId,
								studentMealsRecordId:'',
								ischange:false,
								isEdit:lunchEdit,
							}));
							dinnerlist.push(new Object({
								mealsId:dinnerMealsId,
								mealsTime:kk,
								recordMode:3,
								studentId:studentId,
								studentMealsRecordId:'',
								ischange:false,
								isEdit:dinnerEdit,
							}));
						}
						for(let j=0;j<rowi.mealsEntityList.length;j++){
							let mealsEntity=rowi.mealsEntityList[j];
							//中餐
							if(mealsEntity.type==1){
								let lunch=mealsEntity.studentMealsRecordEntityList||[];
								for(let k=0;k<lunch.length;k++){
									let krow=lunch[k];
									if(krow.recordMode==1||krow.recordMode==2)totalLunch++;//用餐总数
									let idx=dateMap[krow.mealsTime];
									lunchlist[idx]={
										mealsId:krow.mealsId,
										mealsTime:krow.mealsTime,
										recordMode:krow.recordMode,
										studentId:krow.studentId,
										studentMealsRecordId:krow.studentMealsRecordId,
										ischange:false,
										isEdit:mealsEntity.isEdit,
									}
								}
							}
							//晚餐
							else{
								let dinner=mealsEntity.studentMealsRecordEntityList||[];
								for(let k=0;k<dinner.length;k++){
									let krow=dinner[k];
									if(krow.recordMode==1||krow.recordMode==2)totalDinner++;//用餐总数
									let idx=dateMap[krow.mealsTime];
									dinnerlist[idx]={
										mealsId:krow.mealsId,
										mealsTime:krow.mealsTime,
										recordMode:krow.recordMode,
										studentId:krow.studentId,
										studentMealsRecordId:krow.studentMealsRecordId,
										ischange:false,
										isEdit:mealsEntity.isEdit,
									}
								}
							}
						}
						result.push({
							name:studentName,
							totalLunch:totalLunch,
							totalDinner:totalDinner,
							lunch:lunchlist,
							dinner:dinnerlist
						});
					}
					// debugger
					vm.mealFeeList=result;
					vm.dateList=vm.getdateList();
				}
				else{
					vm.$message({type:'warning',message:data.message||'操作失败！'});
				}
			});
		},
		campusChange : function(campusId) { //校区改变
			vm.param.campusId = campusId;
			vm.search();
			vm.loadClass();
		},
		pageSizeChange : function(val) { //页条数发生改变
	  		vm.param.pageSize = val;
	    	vm.search();
	  	},
	  	pageIndexChange : function(val) { //页码发生改变
	    	vm.param.currPage = val;
	    	vm.search(val);
	  	},
	  	getMealClass : function(data) {
			if(!data)return '';
			var list = vm.symbleMap;
			let isedit=data.isEdit==1?'allow_edit':'';
	  		return list[data.recordMode]+' '+isedit;
		},
		selectMealsByDay(index){
			if(index>this.maxEditeIndex)return;
			this.mealFeeList.forEach((meal,index0)=>{
				for(let i=0;i<meal.lunch.length;i++){
					if(i===index){
						let lunch=meal.lunch[i];
						if(lunch.isEdit==1){
							// lunch.recordMode=1;
							// lunch.ischange=true;
							// meal.totalLunch++;
							vm.setMealClass(index0,i,'lunch');
						}
						let dinner=meal.dinner[i];
						if(dinner.isEdit==1){
							// dinner.recordMode=1;
							// dinner.ischange=true;
							// meal.totalDinner++;
							vm.setMealClass(index0,i,'dinner');
						}
						break;
					}
				}
			});
		},
		setMealClass : function(index0,index1,k) {
			if(index1>this.maxEditeIndex)return;
			if(this.mealFeeList[index0][k][index1].isEdit==0){
				// this.$message({type:'warning',message:'该用餐记录已结算，不可编辑！'});
				return;
			}
			let id='mealFeeList-'+k+index0+index1;
			let status=this.mealFeeList[index0][k][index1].recordMode;
			let totalKey=k=='lunch'?'totalLunch':'totalDinner';
			//修改状态
			switch(status){
				case 0:{status=2;this.mealFeeList[index0][totalKey]++;}break;//未用餐 变为 未出勤,有餐
				case 1:{status=0;this.mealFeeList[index0][totalKey]--;}break;//已用餐 变为 未用餐
				case 2:{status=1;/*this.mealFeeList[index0][totalKey]++;*/}break;//未出勤,有餐 变为 已用餐
				case 3:{status=1;this.mealFeeList[index0][totalKey]++;}break;//无记录 变为 已用餐
			}

			var list = vm.symbleMap;
			let classname=list[status];
			let dom=document.getElementById(id);
			list.forEach(str=>{
				dom.classList.remove(str);
			});
			dom.classList.add(classname);
			this.mealFeeList[index0][k][index1].recordMode=status;
			this.mealFeeList[index0][k][index1].ischange=true;
		},
	  	monthChange : function() {
	  		//重设开始结束时间参数,查询班级列表
	  		vm.setStartEndTime();
	  		// vm.loadClass();
	  	},
	  	setStartEndTime : function() {
	  		var month = new Date(vm.month);
			//获取当月第一天
			month.setDate(1);
			vm.param.startTime = tool.DateToString(month, "yyyy-MM-dd");
			//获取当月最后一天
			month.setMonth(month.getMonth()+1);
			month.setDate(0);
			vm.param.endTime = tool.DateToString(month, "yyyy-MM-dd");
	  	},
	  	scroll : function(dir) {
	  		var left = $chartCenter.scrollLeft();
	  		$chartCenter.animate({scrollLeft: left + 5.6 * rem * dir}, 800, "swing");
	  	},
	  	loadClass : function() {
	  		vm.param.classId = "";
	  		// var param = {
	  		// 	campusId: vm.param.campusId,
	  		// 	startTime: vm.param.startTime,
	  		// 	endTime: vm.param.endTime
	  		// }
	  		// api.getclassList(param).then(function(data) {
	  		// 	vm.classList = data.classList;
			//   })
			api.getclassalllist({campusId:vm.param.campusId}).then(function(data){
				if(data.result=='操作成功'){
					vm.classList = data.list;
				}
			});
		},
		saveRecord(){
			let param=[];
			this.mealFeeList.forEach(meal=>{
				for(let i=0;i<meal.lunch.length;i++){
					let lunch=meal.lunch[i];
					if(lunch.ischange){
						param.push(lunch);
					}
					let dinner=meal.dinner[i];
					if(dinner.ischange){
						param.push(dinner);
					}
				}
			});
			if(param.length===0){
				vm.$message({
					type:'warning',
					message:'请先修改餐费记录！'
				});
				return;
			}
			api.mealFeeRecordSave({studentMealsRecordEntityList:param,_wait:true}).then(function(data){
				if(data.resultCode===2000){
					vm.$message({
						type:'success',
						message:'提交成功！'
					});
					vm.search(vm.param.currPage);
				}
				else{
					vm.$message({
						type:'warning',
						message:data.message||'操作失败！'
					});
				}
			});
		},
		/**导出excel */
		exportExcel(){
			//正在导出中
			if(vm.exportstate) {
				return;
			} else {
				vm.exportstate = true;
			}
			vm.exportNotification = vm.$notify({
				title: "模板导出处理中...",
				message: "请稍候，无须重复操作",
				iconClass: "el-icon-loading",
				duration: 0,
				showClose: false
			});

			api.mealFeeRecordTemplate(this.param).then(function(data){
				let blob = new Blob([data.data], {
					type: "application/vnd.ms-excel"
				});
				let filename = decodeURI(
					data.headers["content-disposition"].split(";")[1].split("=")[1]
				);
				let downloadElement = document.createElement("a");
				var href = window.URL.createObjectURL(blob);
				//创建下载的链接
				downloadElement.href = href;
				downloadElement.download = filename;
				//下载后文件名
				document.body.appendChild(downloadElement);
				downloadElement.click();
				//点击下载
				document.body.removeChild(downloadElement);
				//下载完成移除元素
				window.URL.revokeObjectURL(href);

				vm.exportstate = false;

				vm.exportNotification.close();

				vm.exportNotification = vm.$notify({
					type: "success",
					title: "模板导出成功",
					message: "请保存至本地",
					duration: 4000,
					showClose: false
				});
				//释放掉blob对象
				return data.data;
			}).catch(function(e) {
				vm.exportstate = false;
				vm.exportNotification.close();
				vm.exportNotification = vm.$notify({
					title: "",
					type: "error",
					message: "请求数据失败...",
					duration: 2000,
					showClose: false
				});
			});;
		}
	},
	mounted : function() {
		$chartCenter = $(".chart_center");
	},
	created : function() {
		vm = this;
		//设置开始结束参数,查询班级列表
		vm.dateList=vm.getdateList();
		vm.setStartEndTime();
		vm.loadClass();
		
		//请求列表数据
		vm.search();
		
		//获取数据字典对象
		dict = tool.getItem(lsKey.dict,true);
	}
}

</script>

<style lang="scss">
	#meal_fee_record {
		.el-input__inner {
			border-radius: 0.08rem;
			font-size: 0.16rem;
			color: #666666;
			height: 0.36rem;
			line-height: 0.36rem;
		}
		.el-input__icon {
			line-height: 0.36rem;
		}
		
	}
</style>
<style scoped src="@/style/internal_manage/meal_fee_record.css"></style>
<style scoped>
	/*.download_btn {
		
		
		background-image: url(../../assets/img/clue_manage/add_white.png);
	}*/
	
</style>